/**
 *  @author   ghh
 *  @version  1.0
 *  @description 弹窗详情
 */
define(['common', 'request'], function (common, Request) {
    var DialogDetail = function (params) {
        var self = this;
        self.params = $.extend(true, {}, self.params, params);
        self.init();
        // 执行加载完成事件
        self.params.afterPageLoad && typeof (self.params.afterPageLoad) == 'function' && self.params.afterPageLoad(self);
    };
    DialogDetail.prototype.defSelectParam = {
        id: '',//select的ID
        dataAction: 'local',//select的数据加载方式：local本地加载；server服务端加载
        value: '',//跟实体的字段一致
        text: '',//跟界面展示的字段一致
        selectValueField: '',
        selectTextField: '',
        isInitLoadData: true,
        data: [],//本地加载的数据，支持function(){}回调
        template: null,// {input: "#value#", option: "#text#"},
        ajaxParam: {
            url: "",//select 获取列表的url
            urlParam: {},//select获取列表的url的参数
            data: {},//select获取列表的参数
            resultRender: function (data) {
                var result = data["result"];
                return result;
            }
        },
        defaultSelectType: 'index',//初始化默认值选择方式：index 索引；value 值；
        defaultSelectValue: '',// 初始化默认选中值
        defaultSelectIndex: 0,//初始化默认选择索引
        width: 180,//宽度
        placeholder: '',//值为空时提示请选择语句
        isReadOnly: false,//是否只读
        filterMode: "between",//true,
        onCustomFilter: null, //function(opt){return true;}
        onChange: null
    };
    DialogDetail.prototype.defSwitchBtnParam = {
        onValue: true,
        offValue: true,
        beforeChange: function () {
            return true;
        },
        afterChange: null,
        afterBindData: null
    };
    DialogDetail.prototype.params = {
        winCallback: "",//弹出点击确定的回调函数
        formId: '',//表单ID
        getUrl: '',//获取弹窗主体的表单详情
        addUrl: '',//提交新增数据的接口
        updateUrl: '',//提交修改数据的接口
        urlParam: [],//URL传过来的参数
        selectParams: {},
        switchBtnParams: {},
        dialogSelectParams: {},
        panelDialogSelectParams: {},
        beforeLoadPageEvent: "",//页面加载前事件(新增|修改都会进入该方法）
        initBindDataEvent: "",//界面加载完成时(仅html和控件）
        //表单绑定前事件
        beforeBindEvent: null,//只有编辑
        beforeSaveEvent: null,//保存前事件，用来重新保存数据
        //重写保存事件
        overrideSaveEvent: null,
        //保存后事件
        afterSaveEvent: null,
        primaryKeyField: 'id',
        stateField: 'state',
        updateState: "update",//修改状态标志
        addType: 'post',
        updateType: 'put',
        isValidIgnoreHidden: false,
        tabs: [],
        initController: {
            validForm: true,//启用验证控件
            switchBtn: true,//启用开关控件
            inputDialogSelect: true,//是否启用弹窗选中
            panelDialogSelect: true
        },
        validCheck: function () {
            return true;
        },
        isDialog: true,
        afterPageLoad: function (dialogDetail) {
        } //加载完成事件
    };
    DialogDetail.prototype.init = function () {
        var self = this;
        self.jqForm = $("#" + self.params.formId);
        //文本输入框禁用回车
        var inputs = $("input[type='text'],select");
        inputs.keydown(function (e) {
            var k = e.keyCode;
            //var a = $.inArray(this,inputs);//jquery 获取数组元素的下标
            var a=inputs.index($(this));//jquery 获取数组元素的下标,两种方法
            if (k == 13 || k == 39 ) {
                // inputs[a+1].focus();
                return false;
            }
        })

        var state = common.getParamFromUrl(self.params.stateField);
        //页面加载前
        if (typeof (self.params.beforeLoadPageEvent) == "function") {
            self.params.beforeLoadPageEvent();
        }
        /*-----------------------------进行一些默认初始化插件的相关操作--------------------------------*/
        //初始化switchBtn
        if (self.params.initController.switchBtn) {
            $.each(self.params.switchBtnParams, function (index, item) {
                self.params.switchBtnParams[index] = $.extend(true, {}, self.defSwitchBtnParam, item);
            });
            common.initSwitchBtn(self.params.switchBtnParams);
        }
        //初始化inputDialogSelect
        if (self.params.initController.inputDialogSelect) {
            common.initDialogSelect(self.params.dialogSelectParams);
        }
        //初始化select插件
        $.each(self.params.selectParams, function (index, item) {
            item = $.extend(true, {}, self.defSelectParam, item);
            var selId = item["id"];
            self[selId] = new dhtmlXCombo(item["id"], item["value"], item["width"]);
            if (!item["template"]) {
                item["template"] = {
                    input: '#' + item["selectTextField"] + '#',
                    options: '#' + item["selectTextField"] + '#'
                }
            }
            self[selId].setTemplate(item["template"]);
            if (item["placeholder"]) {
                self[selId].setPlaceholder(item["placeholder"]);
            }
            if (item["dataAction"] === "local") {
                var result = [];
                $.each(item["data"], function (idx, itm) {
                    result.push({
                        value: itm[item["selectValueField"]],
                        text: itm[item["selectTextField"]]
                    })
                });
                self[selId].load({options: result});
                if (item["defaultSelectValue"]) {
                    self[item["id"]].setComboValue(item["defaultSelectValue"]);
                }
            } else {
                if (state != self.params.updateState) {
                    if (item["isInitLoadData"]) {
                        self.selLoadServerData(item["id"], function () {
                            self[item["id"]].setComboValue(item["defaultSelectValue"]);
                        });
                    }
                }
            }
            if (item["defaultSelectType"] === "index") {
                self[selId].selectOption(item["defaultSelectIndex"]);
            }
            if (typeof (item["onChange"]) == "function") {
                self[selId].attachEvent("onChange", function (value, text) {
                    item["onChange"](value, text);
                });
            }
            self[selId].enableFilteringMode(item["filterMode"]);
            if (typeof (item["onCustomFilter"]) === "function") {
                self[selId].filter(item["onCustomFilter"]);
            }
            if (typeof (item["isReadOnly"]) == "function" && item["isReadOnly"]) {
                self[selId].disable();
            } else if (typeof (item["isReadOnly"]) != "function" && item["isReadOnly"]) {
                self[selId].disable();
            }
        });
        common.initCalendar();
        if (typeof (self.params.initBindDataEvent) == "function") {
            var initData = self.params.initBindDataEvent();
            self.jqForm.json2form(initData, self.params.initController.switchBtn, self.params.switchBtnParams, self.params.initController.inputDialogSelect);
        }
        //初始化表单验证控件
        if (self.params.initController.validForm) {
            self.validFormObj = common.initValidForm(self.jqForm, self.params.isValidIgnoreHidden);
        }
        /*-----------------------------进行一些默认初始化插件操作结束---------------------------------*/
        //获取状态，判断当是新增还是修改
        var state = common.getParamFromUrl(self.params.stateField);
        var _param = {};
        if (state != self.params.updateState) {
            //新增
            _param["type"] = self.params.addType;
            _param["url"] = self.params.addUrl;
        } else {
            _param["type"] = self.params.updateType;
            _param["url"] = self.params.updateUrl;
            //修改，需要绑定界面初始化事件
            if ($("input[name='" + self.params.primaryKeyField + "']").length === 0) {
                var jqInput = $("<input/>").attr({name: self.params.primaryKeyField, type: 'hidden'});
                $("form").append(jqInput);
            }
            var param = {};
            param[self.params.primaryKeyField] = common.getParamFromUrl(self.params.primaryKeyField);
            if (!self.params.getUrl) {
                return;
            }
            var req = new Request(self.params.getUrl, param);
            req.get({
                success: function (data) {
                    if (data.code === "0") {
                        var result = data.result;
                        if (typeof (self.params.beforeBindEvent) == "function") {
                            result = self.params.beforeBindEvent(data.result);
                        }
                        self.result = result;
                        self.jqForm.json2form(result, self.params.initController.switchBtn, self.params.switchBtnParams, self.params.initController.inputDialogSelect);
                        //绑定select
                        $.each(self.params.selectParams, function (_index, _item) {
                            var item = $.extend(true, {}, self.defSelectParam, _item);
                            var selId = item["id"];
                            if (item["dataAction"] === "local") {
                                self[selId].setComboValue(self.result[item["value"]]);
                            } else {
                                if (item["isInitLoadData"]) {
                                    self.selLoadServerData(selId, function () {
                                        if (self.result[item["value"]]) {
                                            self[selId].setComboValue(self.result[item["value"]]);
                                        }
                                    });
                                }
                            }
                        })
                    }
                }
            });
        }
        var top = common.getTopWindowDom();
        top[self.params.winCallback] = function (index, beforeSaveFn, successFn) {
            if (self.validFormObj.check() && self.params.validCheck()) {
                beforeSaveFn();
                var formData = self.jqForm.form2json();
                if (self.params.initController.switchBtn) {
                    $.each(self.params.switchBtnParams, function (idx, itm) {
                        formData[idx] = formData[idx] ? itm["onValue"] : itm["offValue"];
                    });
                }
                var urlParams = self.params.urlParam;
                $.each(urlParams, function (key, value) {
                    formData[value] = common.getParamFromUrl(value);
                });
                if (typeof (self.params.beforeSaveEvent) == "function") {
                    formData = self.params.beforeSaveEvent(formData);
                }
                var req = new Request(_param["url"], formData);
                req[_param["type"]]({
                    isSuccessTip: true,
                    data: formData,
                    success: function (data) {
                        successFn(data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        var msg = "";
                        if (XMLHttpRequest && XMLHttpRequest.responseJSON && XMLHttpRequest.responseJSON.message) {
                            msg = XMLHttpRequest.responseJSON.message;
                            common.errorMsg(msg);
                        } else {
                            msg = "请求接口异常，稍后尝试！";
                        }
                        successFn({code: "100", msg: msg});
                    }
                })
            }
        };
    };
    DialogDetail.prototype.selLoadServerData = function (selId, callback) {
        var self = this;
        $.each(self.params.selectParams, function (index, item) {
            item = $.extend(true, {}, self.defSelectParam, item);
            if (item["id"] == selId) {
                self[selId].setComboValue("");
                self[selId].setComboText("");
                self[selId].clearAll();
                var ajaxUrlParam = typeof (item.ajaxParam["urlParam"]) == "function" ? item.ajaxParam["urlParam"]() : item.ajaxParam["urlParam"];
                var ajaxDataParam = typeof (item.ajaxParam["data"]) == "function" ? item.ajaxParam["data"]() : item.ajaxParam["data"];
                var req = new Request(item.ajaxParam["url"], ajaxUrlParam);
                req.get({
                    data: ajaxDataParam,
                    success: function (data) {
                        var list = item.ajaxParam["resultRender"](data);
                        var result = [];
                        $.each(list, function (idx, itm) {
                            result.push({
                                value: itm[item["selectValueField"]],
                                text: itm[item["selectTextField"]]
                            })
                        });
                        self[selId].load({options: result});
                        if (self["result"] && self.result[item["value"]]) {
                            self[selId].setComboValue(self.result[item["value"]]);
                        }
                        if (typeof (callback) == "function") {
                            callback(data);
                        }
                    }
                })
            }
        });
    };
    return DialogDetail;
});

